<?php
declare(strict_types=1);
namespace app\shop\logic;
use app\shop\exception\ParamsErrorException;
use app\shop\library\ShopAuth;
use app\shop\library\ShopHelper;
use app\shop\model\order\OrderModel;
use app\shop\model\task\TaskLogModel;
use app\shop\model\task\TaskModel;
use app\shop\service\CouponService;
use think\Collection;
use think\facade\Cache;
use think\facade\Db;
use think\helper\Arr;
use think\Paginator;

class TaskLogic extends BaseLogic
{
    public function __construct()
    {
        $this->model = new TaskModel();
    }

    /**
     * 视频列表
     * @param array $params
     * @return array|Paginator
     */
    public function list(array $params): Paginator|array
    {
        $query = TaskModel::getQuery();
        $where = [];
        $where[] = ['status', '=', 1];
        if(isset($params['region'])){
            $where[] = ['region', '=', $params['region']];
        }else{
            $where[] = ['region', '=', 1];
        }
        $query->where($where);
        $query->order(['weigh' => 'desc']);

        return TaskModel::paginateListQuery($query);
    }

    /**
     * 订单详情
     * @param array $params
     * @return array
     * @throws ParamsErrorException
     */
    public function detail(array $params): array
    {
        if(!isset($params['id'])){
            throw new ParamsErrorException('id不存在');
        }

        $result = $this->model->where('id', $params['id'])->find();
        if (!$result) {
            throw new ParamsErrorException('视频不存在或已被删除');
        }


        $images = Cache::get('image'.$params['user_id']);
        if(!isset($images) || $images==[]){
            $main_store = Db::name('recommend_setting')->where('name','main_store')->value('value');
            if(isset($main_store) && $main_store > 0){
                $main_store_image = Db::name('store_store')->where('radio',1)->value('image');
                if($main_store_image){
                    for($i = 0; $i <= $main_store; $i++){
                        $images[] = ['uid'=>0,'image'=>$main_store_image,'select'=>0];
                    }
                }
            }
            $recommendation = Db::name('recommend_setting')->where('name','recommendation')->value('value');
            if(isset($recommendation) && $recommendation > 0){
                $pinfo = Db::name('shop_user')->where('id', $params['user_id'])->find();
                if($pinfo['examine']>0){
                    $recommendation_info = Db::name('shop_user')->where('examine', $pinfo['examine'])->find();
                    if(isset($recommendation_info) && isset($recommendation_info['qr']) && $recommendation_info['qr'] != '' && $recommendation_info['pstatus'] == 1 && $recommendation_info['pnum'] > 0){
                        for ($i = 0; $i <= $recommendation; $i++) {
                            $images[] = ['uid'=>$recommendation_info['id'],'image'=>$recommendation_info['qr'],'select'=>0];
                        }
                    }

                }
            }
            $upper_level = Db::name('recommend_setting')->where('name','upper_level')->value('value');
            $pids = self::getPid($params['user_id']);
            if(isset($pids)){

                foreach ($pids as $key=>$pid){
                    if(isset($upper_level) && $upper_level > 0 && $key >= $upper_level){
                        break;
                    }
                    $pinfo = Db::name('shop_user')->where('id', $pid)->find();
                    if(isset($pinfo) && isset($pinfo['qr']) && $pinfo['qr'] != '' && $pinfo['pstatus'] == 1 && $pinfo['pnum'] > 0){
                        $images[] = ['uid'=>$pid,'image'=>$pinfo['qr'],'select'=>0];
                    }
                }
                Cache::set('image'.$params['user_id'],$images,24*3600);
            }
        }
        $result->uid = 0;
        $select = 0;
        foreach ($images as $image){
            if($image['select'] == $params['id']){
                $result->image = $image['image'];
                $result->uid = $image['uid'];
                // $result->image_url = $image['image_url'];
                $select = 1;
                break;
            }
        }
        if($select == 0){
            foreach ($images as $k=>$image){
                if($image['select']== 0){
                    $result->image = $image['image'];
                    $result->uid = $image['uid'];
                    $images[$k]['select'] = $params['id'];

                    Cache::delete('image'.$params['user_id']);
                    Cache::set('image'.$params['user_id'],$images,24*3600);
                    break;
                }
            }
        }
        $log = Db::name('task_log')->where('shop_user_id',$params['user_id'])->where('task_task_id',$params['id'])->find();
        $log['avatar'] = $result->image;
        if(isset($log)){
            // dump($log);die();
            // $log->create_time = date('Y-m-d H:i:s', $log->create_time);
            $result->log = $log;
        }else{
            $result->log = [];
        }

        return $result->toArray();
    }

    public function getPid($user_id , $arr=[])
    {
        $user = Db::name('shop_user')->field('id,pid')->where('id', $user_id)->find();
        if(!isset($user) || $user['pid'] == 0){
            return $arr;
        }
        $arr[] = $user['pid'];
        return $this->getPid($user['pid'], $arr);
    }

    public function submit(array $params){
        if(!isset($params['id'])){
            throw new ParamsErrorException('id不存在');
        }
        if(!isset($params['image'])){
            throw new ParamsErrorException('请提交关注视频号截图');
        }
        if(!isset($params['order_id'])){
            $user_info = Db::name('shop_user')->where('id',$params['user_id'])->value('nickname');
            $params['order_id'] = Db::name('store_order')->where('user_name',$user_info)->order('id DESC')->value('order_id');
            if(!isset($params['order_id'])){
                throw new ParamsErrorException('请提交订单号');
            }
            Db::name('store_order')->where('order_id',$params['order_id'])->update(['user_id'=>$params['user_id']]);
        }

        if(Db::name('task_log')->where('shop_user_id',$params['user_id'])->where('task_task_id',$params['id'])->find()){
            throw new ParamsErrorException('已提交审核');
        }
        $data['shop_user_id'] = $params['user_id'];
        $data['task_task_id'] = $params['id'];
        $data['image'] = $params['image'];
        $data['task_task_id'] = $params['id'];
        $data['string'] = $params['order_id'];
        $data['create_time'] = time();
        $result = Db::name('task_log')->insertGetId($data);
        if(!$result){
            throw new ParamsErrorException('保存失败');
        }else{
            return ['msg'=>'保存成功，请等待审核'];
        }

    }

    public function submitLog(array $params){
        $logModel = new TaskLogModel();
        $query = $logModel::getQuery();
        $where = [];
        $where[] = ['shop_user_id', '=', $params['user_id']];
        $query->where($where);
        $res = $logModel::paginateListQuery($query)->each(function($item,$key){
            $item->task_name = $this->model->where('id',$item->task_task_id)->value('name');
            if($item->status == 0){
                $item->status = '未审核';
            }elseif($item->status == 1){
                $item->status = '审核通过';
            }
        });
        return $res;
    }



}